﻿using System;

namespace Devme.Diagnostics
{
    internal sealed class StopwatchContext
    {
        readonly object sync = new object();

        readonly string _name;
        TimeSpan _total;
        uint _count;
        TimeSpan _min;
        TimeSpan _max;

        public StopwatchContext(string name)
        {
            if(string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            _name = name;
            _total = TimeSpan.Zero;
            _count = 0;
            _min = TimeSpan.MaxValue;
            _max = TimeSpan.MinValue;
        }

        public StopwatchResult Refresh(TimeSpan elapsed)
        {
            lock (sync)
            {
                if (elapsed < _min)
                {
                    _min = elapsed;
                }
                if(elapsed > _max)
                {
                    _max = elapsed;
                }
                _total = _total.Add(elapsed);
                _count++;
                return new StopwatchResult(elapsed, _total, _count, _min, _max);
            }
        }
    }
}